package com.gitee.minimalismstyle.fresh.simple.service.impl

import com.gitee.minimalismstyle.fresh.common.core.domain.R
import com.gitee.minimalismstyle.fresh.simple.api.model.TableColumnSchema
import com.gitee.minimalismstyle.fresh.simple.api.model.TableSchema
import com.gitee.minimalismstyle.fresh.simple.api.service.DatabaseService
import com.gitee.minimalismstyle.fresh.simple.api.service.SimpleDatasourceService
import com.gitee.minimalismstyle.fresh.simple.dao.DatabaseDao
import org.springframework.context.annotation.Primary
import org.springframework.stereotype.Service

@Primary
@Service
class DatabaseServiceImpl(
    val databaseDao: DatabaseDao,
    val simpleDatasourceService: SimpleDatasourceService
): DatabaseService {
    override fun findAllTable(datasourceId: Long): R<List<TableSchema>> {
        val simpleDatasource = simpleDatasourceService.findById(datasourceId).get()
        return R.success(databaseDao.findAllTable(simpleDatasource.getDatabase()))
    }

    override fun findTableByName(datasourceId: Long, name: String): R<TableSchema> {
        val simpleDatasource = simpleDatasourceService.findById(datasourceId).get()
        val table = databaseDao.findTableByName(simpleDatasource.getDatabase(), name)
        table.columns = databaseDao.findColumnsByName(simpleDatasource.getDatabase(), name)
        var pk = table.columns.find { it.isPk }
        if(pk != null){
            table.pk = pk
        }

        return R.success(table)
    }

    override fun findColumnsByName(datasourceId: Long, name: String): R<List<TableColumnSchema>> {
        val simpleDatasource = simpleDatasourceService.findById(datasourceId).get()
        return R.success(databaseDao.findColumnsByName(simpleDatasource.getDatabase(), name))
    }
}